// ==UserScript==
// @name         bili 获取AV号
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  bili 获取AV号
// @author       Laicy <2708799299@qq.com>
// @compatible   chrome
// @include      *.bilibili.com/*
// @require      https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js
// @grant        GM_xmlhttpRequest
// @grant        GM_download
// ==/UserScript==

(function() {
  'use strict';
  var button = "<a id='biliOK' style='position: fixed;z-index: 101;left: 0;top: 50%;margin-top: 44px;width: 28px;height: 100px;"+
    "border-top-right-radius: 2px;border-bottom-right-radius: 2px;background-color: #78deaa;transition: all .3s;"+
    "font-size: 12px;color: #fff;box-shadow: 0 6px 10px 0 rgba(134,253,138,0.4);padding: 8px 7px;line-height: 14px;box-sizing: border-box;"+
    "text-decoration: none;outline: none;cursor: pointer;'>查询当前AV号</a>";
    $('body').append(button);
})();

$('#biliOK').click(function(){
  // 跨域获取av号
  handleId(getId());
})

// 获取av或bv号
function getId() {
  let queryArray = window.location.pathname.split("/");
  let id = queryArray[queryArray.length];
  if (!id) {
    return queryArray[queryArray.length - 1];
  } else {
    return id;
  }
}

// 处理类型
function handleId(id) {
  let type = id.substring(0, 2).toLowerCase();
  let idNum = id.substr(2);
  if (type == 'av') {
    // av号
    handleData(idNum, 1);
  } else if (type == 'bv') {
    // bv号
    handleData(idNum, 2);
  }
}

// 跨域获取视频信息
function handleData(id ,type) {
  var param;
  if (type == 1) {
    param = "aid=" + id;
  } else if (type == 2) {
    param = "bvid=" + id;
  }
  console.log(param)
  GM_xmlhttpRequest({
    method: "GET",
    url: "https://api.bilibili.com/x/web-interface/view?" + param,
    headers: {"Content-type":"application/json;","Accept":"application/json"},
    onload: function(response) {
      let res = JSON.parse(response.response)
      if (res.code === 0) {
        alert("当前视频的av号：" + res.data.aid)
      } else {
        alert("找不到。。。")
      }
    }
  });
}
